import { createRouter, createWebHashHistory } from "vue-router";
import Login from "../components/Login/index.vue";
import Layout from "../components/Layout/index.vue";
import Error404 from "../components/404/index.vue";
import systemParams from '@/utils/systemParams.js'
import { storeToRefs } from 'pinia'
import { useRouteMenu } from '@/store/menu.store.js'
import api from '@/api/getToken'


// 常驻路由
const routes = [
  {
    path: "/",
    name: "login",
    meta: {
      title: '登录页'
    },
    component: Login,
  },
  {
    path: "/dashboard",
    name: "dashboard",
    meta: {
      title: '专门的首页'
    },
    component: '',
  },
  {
    path: "/layout",
    name: "layout",
    meta: {
      title: '布局'
    },
    component: Layout,
    redirect: '/food',
    children: []
  },
];
// 是否需要专门的首页
if(!systemParams.is_need_a_homepage) routes.splice(1, 1)

let router = createRouter({
  history: createWebHashHistory(),
  routes,
});

const joinRoute = (menu) => {
  const recursion = (data) => {
    data.forEach(item => {
      let obj = {
        path: item.path,
        name: item.name,
        meta: item.meta,
      }
      if(item.children && item.children.length !== 0){
        recursion(item.children)
      }else {
        router.addRoute("layout", {
          path: item.path,
          name: item.name,
          meta: item.meta,
          component: () => import(`@/views/${ item.component }/index.vue`),
        });
      }
    })
  }
  router.addRoute({
    path: "/:path(.*)*",
    name: "404",
    component: Error404,
  });
  recursion(menu)
}

// 是否登录标识
let isLogin = false


router.beforeEach(async(to, from, next) => {
  if (!localStorage.getItem("token") && to.path !== "/") {
    ElMessage.warning("token已过期或者不存在, 请重新登录 !");
    next({ path: "/" });
  }
  if(to.path === "/") isLogin = false

  // 如果是登录进去了，就设置一次路由
  if(from.path === "/" && to.path !== "/") {
    if(isLogin) next()
    else {
      const store = useRouteMenu();
      let menu = await store.setMenu()
      // 添加路由
      joinRoute(menu)
      next(to.path)
      isLogin = true
    }
  }else {
    next()
  }
})

export default router;
